<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { FormType } from './ticket.ts'
import { GetBrandoffialTicketDetail, PostCreateTicketData, PutModifyTicketData } from '@/api/modules/brandofficial'
import detailStore from '@/store/modules/NewCacheData'
import { GetAllData as GetProductOption } from '@/api/modules/merchandiseControl'
import { GetOptionData as GetCouponOption } from '@/api/modules/voucher'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const id = route.query.id as string
// const imgDomain = 'https://img1.eprhan.cc'

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>({
  bannerPic: '',
  ruleBtnPic: '',
  rulePic: '',
  ticketId: 0,
  ticketBgpic: '',
  bannerTxtPic: '',
  productIds: [],
  shareBtnPic: '',
  qrcodeBtnPic: '',
  qrcodeBgpic: '',
  status: 0,
  sharePic: '',
  shareTxt: '',
})

const OptionObj = reactive({
  couponOption: [] as any[],
  productOption: [] as any[],
})

const rules = reactive({
  shareTxt: [
    { required: true, message: '请输入分享语', trigger: 'blur' },
  ],
  sharePic: [
    { required: true, message: '请上传分享图', trigger: 'blur' },
  ],
  bannerPic: [
    { required: true, message: '请上传顶部banner图', trigger: 'blur' },
  ],
  bannerTxtPic: [
    { required: true, message: '请上传分栏图', trigger: 'blur' },
  ],
  ruleBtnPic: [
    { required: true, message: '请上传活动规则按钮图', trigger: 'blur' },
  ],
  rulePic: [
    { required: true, message: '请上传活动规则图', trigger: 'blur' },
  ],
  ticketBgpic: [
    { required: true, message: '请上传券背景图', trigger: 'blur' },
  ],
  ticketId: [
    { required: true, message: '请选择优惠券', trigger: 'blur' },
  ],
  shareBtnPic: [
    { required: true, message: '请上传分享按钮图', trigger: 'blur' },
  ],
  qrcodeBtnPic: [
    { required: true, message: '请上传二维码按钮图', trigger: 'blur' },
  ],
  qrcodeBgpic: [
    { required: true, message: '请上传二维码背景图', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'blur' },
  ],
  productIds: [
    { required: true, message: '请选择关联商品', trigger: 'blur' },
  ],
})

// 图片上传赋值
function handleUploadSuccess(url: string, key: string) {
  // eslint-disable-next-line ts/ban-ts-comment
  // @ts-expect-error
  ruleForm.value[key] = url
}

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      const params = {
        ...ruleForm.value,
      }

      params.productIds = (params.productIds as number[]).join(',')
      if (id) {
        // 编辑
        params.id = id
        PutModifyTicketData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('编辑成功')
            router.push({ name: 'brandofficialTicket' })
          }
        })
      }
      else {
        // 添加
        PostCreateTicketData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('添加成功')
            detailData.emptyFormData('brandoffcialTicketFrom')
            router.push({ name: 'brandofficialTicket' })
          }
        })
      }
    }
  })
}

onMounted(async () => {
  if (id) {
    await GetBrandoffialTicketDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
      }
    })
  }
  else {
    ruleForm.value = detailData.getFormData('brandoffcialTicketFrom')
  }

  ruleForm.value.productIds = (ruleForm.value.productIds as string).split(',').map((item: any) => {
    return Number(item)
  })

  await GetCouponOption('1').then((res) => {
    OptionObj.couponOption = res.data
  })

  await GetProductOption().then((res) => {
    OptionObj.productOption = res.data
  })

  watch(ruleForm, (newValue) => {
    if (!id) {
      detailData.rememberFormData('brandoffcialTicketFrom', newValue)
    }
  }, { deep: true })
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :model="ruleForm" :rules="rules">
      <PageMain title="裂变券">
        <ElRow :gutter="20">
          <ElCol :md="3">
            <ElFormItem label="状态">
              <el-switch
                v-model="ruleForm.status"
                :active-value="1"
                :inactive-value="-1"
                active-text="启用"
                inactive-text="停用"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="5">
            <ElFormItem label="绑定券" prop="ticketId">
              <el-select
                v-model="ruleForm.ticketId"
                filterable
                placeholder="请选择绑定的券"
              >
                <el-option
                  v-for="item in (OptionObj.couponOption as any[])"
                  :key="item.id"
                  :label="`${item.id}-${item.name}`"
                  :value="item.id"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="16">
            <ElFormItem label="关联商品" prop="productIds">
              <el-select
                v-model="ruleForm.productIds"
                filterable
                multiple
                placeholder="请选择关联的商品"
                style="min-width: 900px;"
              >
                <el-option
                  v-for="item in (OptionObj.productOption as any[])"
                  :key="item.productId"
                  :label="`${item.productId}-${item.productName}`"
                  :value="item.productId"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="分享语" prop="shareTxt">
              <el-input v-model="ruleForm.shareTxt" style="max-width: 500px;" placeholder="请输入分享语" type="textarea" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="分享图" prop="sharePic">
              <ImageUpload
                :ext="['jpg', 'png']" height="150" width="auto" :size="5"
                :url="ruleForm.sharePic" @on-success="(url: string) => handleUploadSuccess(url, 'sharePic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="顶部banner图" prop="bannerPic">
              <ImageUpload
                :ext="['jpg', 'png']" height="150" width="auto" :size="5"
                :url="ruleForm.bannerPic" @on-success="(url: string) => handleUploadSuccess(url, 'bannerPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="活动规则按钮图（72*138）" prop="ruleBtnPic">
              <ImageUpload
                :ext="['jpg', 'png']" height="150" width="auto" :size="5"
                :url="ruleForm.ruleBtnPic" @on-success="(url: string) => handleUploadSuccess(url, 'ruleBtnPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="活动规则图" prop="rulePic">
              <ImageUpload
                :ext="['jpg', 'png']" height="150" width="auto" :size="5"
                :url="ruleForm.rulePic" @on-success="(url: string) => handleUploadSuccess(url, 'rulePic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="券背景图" prop="ticketBgpic">
              <ImageUpload
                :ext="['jpg', 'png']" height="150" width="auto" :size="5"
                :url="ruleForm.ticketBgpic" @on-success="(url: string) => handleUploadSuccess(url, 'ticketBgpic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="分栏图（553*47）" prop="bannerTxtPic">
              <ImageUpload
                :ext="['jpg', 'png']" height="150" width="auto" :size="5"
                :url="ruleForm.bannerTxtPic" @on-success="(url: string) => handleUploadSuccess(url, 'bannerTxtPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="转发按钮图（90*90）" prop="shareBtnPic">
              <ImageUpload
                :ext="['jpg', 'png']" height="150" width="auto" :size="5"
                :url="ruleForm.shareBtnPic" @on-success="(url: string) => handleUploadSuccess(url, 'shareBtnPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="海报按钮图（90*90）" prop="qrcodeBtnPic">
              <ImageUpload
                :ext="['jpg', 'png']" height="150" width="auto" :size="5"
                :url="ruleForm.qrcodeBtnPic" @on-success="(url: string) => handleUploadSuccess(url, 'qrcodeBtnPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="海报背景图" prop="qrcodeBgpic">
              <ImageUpload
                :ext="['jpg', 'png']" height="150" width="auto" :size="5"
                :url="ruleForm.qrcodeBgpic" @on-success="(url: string) => handleUploadSuccess(url, 'qrcodeBgpic')"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}

.hint {
  display: flex;
  align-items: center;
  margin-left: 10px;
}
</style>
